using System.Text.Encodings.Web;
using System.Text.Json;
using HKH.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Newtonsoft.Json.Serialization;
using Quartz;
using SyncService.Common;
using SyncService.HostExtension;
using SyncService.WebHost.Filters;

var _encoderField = typeof(JsonSerializerOptions).GetField("_encoder", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
_encoderField?.SetValue(JsonSerializerOptions.Default, JavaScriptEncoder.UnsafeRelaxedJsonEscaping);

var builder = WebApplication.CreateBuilder(args);
Constants.BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
Constants.ContentRootPath = builder.Environment.ContentRootPath;
Constants.WebRootPath = builder.Environment.WebRootPath;
// Add services to the container.

builder.Services.AddControllers(o => o.Filters.Add(typeof(ExceptionFilter))).AddNewtonsoftJson();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

ConfigureServices(builder.Services);



ParallelTaskPool.Start(builder.Configuration);

var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
app.UseSwagger();
app.UseSwaggerUI();
//}

//app.UseHttpsRedirection();

app.UseAuthorization();
app.MapHealthChecks("/health");
app.MapControllers();
app.UseDefaultFiles();

app.UseStaticFiles();
app.Run();

void ConfigureServices(IServiceCollection services)
{
    services.AddMemoryCache();
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddHealthChecks().AddCheck("health", () => HealthCheckResult.Healthy());

    services.ConfigureWebHost();

    services.AddQuartzHostedService(options =>
    {
        options.WaitForJobsToComplete = true;
    });
}